package com.example.day9_sqlite;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class MusicDao {

    //数据库的两个对象
    private MusicSqlite musicSqlite;
    SQLiteDatabase db;
    //单例模式---懒汉模式  饿汉模式
    //构造私有化  声明变量   对外公开
    private MusicDao(Context context){
        musicSqlite = new MusicSqlite(context);
        db = musicSqlite.getWritableDatabase();
    }
    //饿汉模式---直接实例化
    //private static MusicDao musicDao = new MusicDao();
    //懒汉模式--什么时候调用什么时候实例化
    private static MusicDao musicDao;

    public static MusicDao getInstance(Context context){
        if(musicDao==null){
            musicDao = new MusicDao(context);
        }
        return musicDao;
    }

    //收藏音乐
    public void insert(MusicEntity.DataBean bean){
        ContentValues values  = new ContentValues();
        values.put("id",bean.getId());
        values.put("name",bean.getName());
        values.put("picUrl",bean.getPicUrl());
        values.put("duration",bean.getDuration());
        values.put("singer",bean.getSinger());
        db.insert("music",null,values);
    }
    //查询收藏音乐
    @SuppressLint("Range")
    public List<MusicEntity.DataBean> query(String key,String name){
        List<MusicEntity.DataBean> list = new ArrayList<>();
        Cursor cursor;
        if(key.isEmpty()){
            cursor = db.query("music", null, null, null, null, null, null);
        }else{
            cursor = db.query("music",null,key+"=?",new String[]{name},null,null,null);
        }
        if(cursor!=null){
            while (cursor.moveToNext()){
                 int id = cursor.getInt(cursor.getColumnIndex("id"));
                 int duration = cursor.getInt(cursor.getColumnIndex("duration"));
                String name1 = cursor.getString(cursor.getColumnIndex("name"));
                String picUrl = cursor.getString(cursor.getColumnIndex("picUrl"));
                String singer = cursor.getString(cursor.getColumnIndex("singer"));
                MusicEntity.DataBean dataBean = new MusicEntity.DataBean();
                dataBean.setId(id);
                dataBean.setName(name1);
                dataBean.setDuration(duration);
                dataBean.setPicUrl(picUrl);
                dataBean.setSinger(singer);
                list.add(dataBean);
            }
            cursor.close();
        }

        return list;
    }
    //移除收藏数据
    public void delete(String name){
        db.delete("music","name=?",new String[]{name});
    }

}
